package com.richest.api.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.richest.api.service.IAdmartService;
import com.richest.api.service.IAdvertsDetailService;
import com.richest.api.service.IAdvertsService;
import com.richest.api.service.ICategoryService;
import com.richest.api.service.ISysConfigService;
import com.richest.api.service.IUserCollectRecordService;
import com.richest.api.service.IUserService;
import com.richest.bean.AdmartBean;
import com.richest.bean.AdvertsBean;
import com.richest.bean.CategoryBean;
import com.richest.bean.UserBean;
import com.richest.bean.UserCollectRecordBean;
import com.richest.constant.StringConstant;
import com.richest.util.CallResults;
import com.richest.util.JSONUtil;
import com.richest.util.StringUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;

/**
 * 搜索框
 * 
 * @author zhaohongchao 2019.02.20
 */
@RestController
@RequestMapping("/commonController")
@Api(value = "通用接口")
@EnableAutoConfiguration
@MultipartConfig
public class ApiCommonController {
//	private Logger logger = LoggerFactory.getLogger(ApiCommonController.class);

	@Autowired
	private IAdvertsService advertsService; // 轮播
	@Autowired
	private IAdvertsDetailService advertsDetailService; // 轮播详情
	@Autowired
	private ICategoryService categoryService; // 分类
	@Autowired
	private IAdmartService admartService; // 商户
	@Autowired
	private IUserService userService; // 用户
	@Autowired
	private IUserCollectRecordService userCollectRecordService; // 用户收藏
	@Autowired
	private ISysConfigService sysConfigService;

	/**
	 * 搜索框
	 *
	 * @author zhaohongchao 2019/2/20 0020
	 * @param
	 * @return
	 **/
	@RequestMapping(value = "search", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "搜索框", value = "搜索框", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "longitude", value = "横坐标", required = true, paramType = "query", dataType = "BigDecimal"),
			@ApiImplicitParam(name = "latitude", value = "纵坐标", required = true, paramType = "query", dataType = "BigDecimal"),
			@ApiImplicitParam(name = "keys", value = "值", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "pageNo", value = "页码", required = true, paramType = "query", dataType = "Integer", defaultValue = "0"),
			@ApiImplicitParam(name = "pageSize", value = "记录数", required = true, paramType = "query", dataType = "Integer", defaultValue = "5") })
	public CallResults search(@RequestParam BigDecimal longitude, @RequestParam BigDecimal latitude,
			/* @RequestParam String type, */@RequestParam String keys, @RequestParam Integer pageNo,
			@RequestParam Integer pageSize) {
		List<Map<String, Object>> lstAdmart = new ArrayList<>();
		// 组织查询条件
		Map<String, Object> params = new HashMap<>();
		params.put("keys", keys);
		params.put("page", pageNo);
		params.put("size", pageSize);
		params.put("longitude", longitude);
		params.put("latitude", latitude);
		lstAdmart = admartService.search(params);
		/*
		 * if ("name".equals(type)) { // 按商户名称 lstAdmart =
		 * admartService.searchByName(params); } else if ("type".equals(type)) { //
		 * 按商户类型 lstAdmart = admartService.searchByType(params); }
		 */
		return CallResults.ok("搜索成功").put("data", lstAdmart);
	}

	/**
	 * banner列表
	 *
	 * @Author zhaohongchao 2019/2/20 0020
	 * @Param
	 * @return
	 **/
	@RequestMapping(value = "getAdverts", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "banner列表", value = "banner列表", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "biz_type", value = "类型：01订餐类", required = true, paramType = "query", dataType = "Integer"),
			@ApiImplicitParam(name = "name", value = "名称：banner 轮播，activity 活动", required = true, paramType = "query", dataType = "String") })
	public CallResults getAdverts(@RequestParam Integer biz_type, @RequestParam String name) {
		// 查询轮播对象
		AdvertsBean advertsBean = new AdvertsBean();
		advertsBean.setBiz_type(biz_type);
		advertsBean.setName(name);
		advertsBean.setStatus(0);
		advertsBean = advertsService.selectOne(advertsBean);

		// 查询轮播详细信息

		List<Map<String, Object>> lst = advertsDetailService.selectList(advertsBean.getAdverts_id());

		// 组织返回
		JSONObject jsonResult = new JSONObject();
		jsonResult.put("advertsId", advertsBean.getAdverts_id());
		jsonResult.put("continuedTime", advertsBean.getContinued_time());
		jsonResult.put("list", lst);
		jsonResult.put("length", lst.size());

		return CallResults.ok().put("data", jsonResult);
	}

	/**
	 * 首页分类列表
	 *
	 * @author zhaohongchao 2019/2/22 0022
	 * @param
	 * @return
	 **/
	@RequestMapping(value = "getCategoryList", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "首页分类列表", value = "首页分类列表", httpMethod = "GET")
	@ApiImplicitParam(name = "biz_type", value = "业务类型：01-餐饮", required = true, paramType = "query", dataType = "Integer")
	public CallResults getCategoryList(@RequestParam Integer biz_type) {
		// 查询状态为正常的分类
		CategoryBean categoryBean = new CategoryBean();
		categoryBean.setStatus(0);
		categoryBean.setType(1);
		categoryBean.setBiz_type(biz_type);
		categoryBean.setParent_id(0L);
		List<Map<String, Object>> lstOneCategory = categoryService.selectList(categoryBean);

		for (Map<String, Object> map : lstOneCategory) {
			categoryBean.setStatus(0);
			categoryBean.setType(2);
			categoryBean.setBiz_type(biz_type);
			categoryBean.setParent_id(Long.valueOf(map.get("category_id").toString()));

			List<Map<String, Object>> lstTwoCategory = categoryService.selectList(categoryBean);
			map.put("list", lstTwoCategory);
		}

		return CallResults.ok().put("data", lstOneCategory);
	}

	/**
	 * 收藏接口
	 * 
	 * @author zhaohongchao 2019年4月2日 上午9:51:44
	 * @email 70375739@qq.com
	 * @param user_id
	 * @param collect_id
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "collect", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "收藏", value = "收藏", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "user_id", value = "用户id", required = true, paramType = "query", dataType = "Long"),
			@ApiImplicitParam(name = "collect_id", value = "店铺/菜品id", required = true, paramType = "query", dataType = "Long") })
	public CallResults collect(@RequestParam Long user_id, @RequestParam Long collect_id) {
		UserBean userBean = new UserBean();
		userBean.setUser_id(user_id);
		userBean = userService.selectOne(userBean);
		if (null == userBean) {
			return CallResults.error("不存在有效的用户信息");
		}

		AdmartBean admartBean = admartService.selectById(collect_id);
		if (null == admartBean) {
			return CallResults.error("不存在有效的店铺信息");
		}
		UserCollectRecordBean userCollectRecordBean = userCollectRecordService.getAdmartCollectStatus(user_id,
				collect_id);
		if (null != userCollectRecordBean) {
			return CallResults.error("店铺已被收藏");
		}
		userCollectRecordBean = new UserCollectRecordBean();
		userCollectRecordBean.setCollect_id(collect_id);
		userCollectRecordBean.setUser_id(user_id);
		userCollectRecordBean.setType(1);
		userCollectRecordBean.setCreate_by(String.valueOf(user_id));
		userCollectRecordBean.setCreate_time(new Date());
		userCollectRecordBean.setStatus(1);
		userCollectRecordBean.setStatus_name("正常");
		return CallResults.ok().put("data", userCollectRecordService.insert(userCollectRecordBean));
	}

	/**
	 * 取消收藏
	 * 
	 * @author zhaohongchao 2019年4月2日 上午9:51:36
	 * @email 70375739@qq.com
	 * @param user_id
	 * @param collect_id
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "cancelCollect", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "取消收藏", value = "收藏", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "user_collect_record_id", value = "收藏id", required = true, paramType = "query", dataType = "Long"),
			@ApiImplicitParam(name = "user_id", value = "用户id", required = true, paramType = "query", dataType = "Long") })
	public CallResults cancelCollect(@RequestParam Long user_collect_record_id, @RequestParam Long user_id) {
		UserCollectRecordBean userCollectRecordBean = new UserCollectRecordBean();
		userCollectRecordBean.setUser_collect_record_id(user_collect_record_id);
		userCollectRecordBean.setStatus(0);
		userCollectRecordBean.setStatus_name("取消收藏");
		userCollectRecordBean.setUpdate_by(String.valueOf(user_id));
		userCollectRecordBean.setUpdate_time(new Date());
		userCollectRecordService.update(userCollectRecordBean);
		return CallResults.ok();
	}

	/**
	 * 获取收藏列表
	 * 
	 * @author zhaohongchao 2019年4月2日 上午9:51:36
	 * @email 70375739@qq.com
	 * @param user_id
	 * @param collect_id
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "getCollectList", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "获取收藏列表", value = "收藏", httpMethod = "GET")
	@ApiImplicitParam(name = "user_id", value = "用户id", required = true, paramType = "query", dataType = "Long")
	public CallResults getCollectList(@RequestParam Long user_id) {
		UserBean userBean = new UserBean();
		userBean.setUser_id(user_id);
		userBean = userService.selectOne(userBean);
		if (null == userBean) {
			return CallResults.error("不存在有效的用户信息");
		}

		return CallResults.ok().put("data", userCollectRecordService.selectList(user_id));
	}

	/**
	 * 查看店铺是否被收藏
	 * 
	 * @author zhaohongchao 2019年4月2日 上午9:51:36
	 * @email 70375739@qq.com
	 * @param user_id
	 * @param collect_id
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "getAdmartCollectStatus", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "查看店铺是否被收藏", value = "收藏", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "user_id", value = "用户id", required = true, paramType = "query", dataType = "Long"),
			@ApiImplicitParam(name = "admart_id", value = "店铺id", required = true, paramType = "query", dataType = "Long") })
	public CallResults getAdmartCollectStatus(@RequestParam Long user_id, @RequestParam Long admart_id) {
		UserBean userBean = new UserBean();
		userBean.setUser_id(user_id);
		userBean = userService.selectOne(userBean);
		if (null == userBean) {
			return CallResults.error("不存在有效的用户信息");
		}

		AdmartBean admartBean = admartService.selectById(admart_id);
		if (null == admartBean) {
			return CallResults.error("不存在有效的店铺信息");
		}

		UserCollectRecordBean userCollectRecordBean = new UserCollectRecordBean();
		userCollectRecordBean = userCollectRecordService.getAdmartCollectStatus(user_id, admart_id);
		// 是否被收藏，0-未收藏；1-已收藏
		int status = 0;
		if (null != userCollectRecordBean) {
			status = 1;
		}

		return CallResults.ok().put("data", status);
	}

	@RequestMapping(value = "ossUpload", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "图片上传", value = "图片上传", httpMethod = "POST")
	@ApiImplicitParam(name = "file", value = "文件体", required = true, dataType = "MultipartFile")
	@ResponseBody
	public String ossupload(HttpServletRequest servletRequest, @RequestBody MultipartFile file) throws IOException {
		JSONObject resultObject = new JSONObject();
		String tag = servletRequest.getParameter("tag");
		String username = servletRequest.getParameter("username");
		String prefix = "";
		if (StringUtil.isNotNullOrEmpty(tag)) {
			if (tag.equals("1")) {
				prefix = StringConstant.FILE_UPLOAD_ADVERTS;// 广告详情上传图片
			} else if (tag.equals("2")) {
				prefix = StringConstant.FILE_UPLOAD_CATEGORY;// 店铺分类图标
			} else if (tag.equals("3")) {
				prefix = StringConstant.FILE_UPLOAD_EXTENSION;// 活动详情图片
			} else if (tag.equals("4")) {
				prefix = StringConstant.FILE_UPLOAD_USER_HEAD;// 用户头像
			} else if (tag.equals("5")) {
				prefix = StringConstant.FILE_UPLOAD_GOOD_IMAGE;// 菜品图片
			} else if (tag.equals("6")) {
				prefix = StringConstant.FILE_UPLOAD_ADMART_IMAGE;// 店铺图片
			}
		}
		if (StringUtil.isNotNullOrEmpty(username)) {
			prefix = prefix + "/" + username;
		}
		// 如果文件内容不为空，则写入上传路径
		if (!file.isEmpty()) {
			// 上传文件
			// 返回的是一个url对象
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			String url = sysConfigService.getCloudStorageService().uploadPrefixSuffix(file.getBytes(), prefix, suffix);
			if (StringUtil.isNotNullOrEmpty(url)) {
				resultObject.put("returnUrl", url);
				return JSONUtil.returnSuccessString(resultObject);
			} else {
				return JSONUtil.returnErrorString(null, "上传失败！");
			}
		}
		return JSONUtil.returnErrorString(null, "未找到上传内容！");
	}
}
